#include "netdriver.h"
#include <QTcpSocket>
#include <QDebug>
netDriver *netDriver::obj =nullptr;
netDriver::netDriver(QObject *parent) : QObject(parent)
  ,client(new QTcpSocket)
{
connect(client,&QTcpSocket::readyRead,this,&netDriver::netReadyReadSlot);
}

netDriver *netDriver::getObject()
{
if(obj == nullptr)
    obj = new netDriver;
return obj;
}

bool netDriver::netConnect(QString ip, quint16 port)
{qDebug () << ip << "<<" << port;
    netDisconnect();
    client->connectToHost(ip,port);
    return client->waitForConnected(2000);
}

void netDriver::netDisconnect()
{
   if(client->state() == QTcpSocket::ConnectedState )
       client->disconnectFromHost();
}

bool netDriver::netWrite(const QByteArray &data)
{
if(!netGetState())
    return false;
  qint64  len= client->write(data);//做长度是否相等的校验，来判断数据是否发送完整
  return len == data.length() ? true : false;
}

bool netDriver::netGetState()
{
    return client->state() == QTcpSocket::ConnectedState ? true : false;
}

void netDriver::netReadyReadSlot()
{ qDebug() << "qishi shi shou dao le ";
QByteArray data =client->readAll();
emit netRead(data);
}

